import { ref } from 'vue'
import { getCurrentUser, getUserId } from './userStore'

// 优惠券接口定义
export interface Coupon {
  id: string
  name: string
  amount: number
  minAmount: number // 最低消费金额
  type: 'discount' | 'cash' // 折扣券或现金券
  status: 'available' | 'used' | 'expired'
  expireDate: string
  description: string
  source: string // 获得来源
  createTime: string
}

const coupons = ref<Coupon[]>([])

// 初始化默认优惠券
function initDefaultCoupons() {
  const futureDate = new Date();
  futureDate.setMonth(futureDate.getMonth() + 2); // 设置为2个月后过期
  const expireDateStr = futureDate.toISOString().slice(0, 10);
  
  const defaultCoupons: Coupon[] = [
    {
      id: 'coupon_001',
      name: '新用户专享券',
      amount: 12.00,
      minAmount: 50,
      type: 'cash',
      status: 'available',
      expireDate: expireDateStr, // 使用未来日期
      description: '满50元可用',
      source: '新用户注册',
      createTime: new Date().toISOString().slice(0, 10)
    },
    {
      id: 'coupon_002',
      name: '运动达人券',
      amount: 20.00,
      minAmount: 100,
      type: 'cash',
      status: 'available',
      expireDate: '2024-12-31',
      description: '满100元可用',
      source: '运动打卡奖励',
      createTime: new Date().toISOString().slice(0, 10)
    },
    {
      id: 'coupon_003',
      name: '健身器材券',
      amount: 30.00,
      minAmount: 200,
      type: 'cash',
      status: 'available',
      expireDate: '2024-12-31',
      description: '满200元可用',
      source: '商城活动',
      createTime: new Date().toISOString().slice(0, 10)
    },
    {
      id: 'coupon_004',
      name: '已使用券',
      amount: 15.00,
      minAmount: 80,
      type: 'cash',
      status: 'used',
      expireDate: '2024-12-31',
      description: '满80元可用',
      source: '签到奖励',
      createTime: '2024-11-15'
    }
  ]
  
  console.log('初始化默认优惠券:', defaultCoupons);
  return defaultCoupons;
}

// 修改获取可用优惠券的方法，添加更多调试信息
export function getAvailableCoupons(minAmount: number = 0) {
  const now = new Date();
  console.log('当前时间:', now.toISOString());
  
  const available = coupons.value.filter(coupon => {
    const isStatusAvailable = coupon.status === 'available';
    const isAmountValid = minAmount >= coupon.minAmount;
    const expireDate = new Date(coupon.expireDate);
    const isNotExpired = expireDate > now;
    
    console.log(`优惠券检查 ${coupon.name}:`, {
      状态: coupon.status,
      状态可用: isStatusAvailable,
      金额要求: `${minAmount} >= ${coupon.minAmount}`,
      金额满足: isAmountValid,
      过期日期: coupon.expireDate,
      未过期: isNotExpired,
      最终结果: isStatusAvailable && isAmountValid && isNotExpired
    });
    
    return isStatusAvailable && isAmountValid && isNotExpired;
  });
  
  console.log('可用优惠券结果:', available);
  return available;
}

// 使用优惠券
export function useCoupon(couponId: string) {
  const coupon = coupons.value.find(c => c.id === couponId)
  if (coupon && coupon.status === 'available') {
    coupon.status = 'used'
    saveUserCoupons()
    return true
  }
  return false
}

// 添加新优惠券
export function addCoupon(couponData: Omit<Coupon, 'id' | 'createTime'>) {
  const newCoupon: Coupon = {
    ...couponData,
    id: `coupon_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`,
    createTime: new Date().toISOString().slice(0, 10)
  }
  
  coupons.value.unshift(newCoupon)
  saveUserCoupons()
  return newCoupon
}

// 获取优惠券统计
// 获取优惠券统计
export function getCouponStats() {
  const now = new Date();
  
  // 可用：状态为available且未过期
  const available = coupons.value.filter(c => 
    c.status === 'available' && new Date(c.expireDate) > now
  ).length;
  
  // 已用：状态为used
  const used = coupons.value.filter(c => c.status === 'used').length;
  
  // 过期：状态为expired或已过期
  const expired = coupons.value.filter(c => 
    c.status === 'expired' || new Date(c.expireDate) <= now
  ).length;
  
  return { available, used, expired, total: coupons.value.length };
}

// 加载用户优惠券
export function loadUserCoupons() {
  try {
    const userId = getUserId()
    const storageKey = `userCoupons_${userId}`
    const storedCoupons = localStorage.getItem(storageKey)
    
    if (storedCoupons) {
      coupons.value = JSON.parse(storedCoupons)
    } else {
      // 首次使用，初始化默认优惠券
      coupons.value = initDefaultCoupons()
      saveUserCoupons()
    }
    console.log('优惠券加载完成:', coupons.value)
  } catch (error) {
    console.error('加载优惠券失败:', error)
    coupons.value = initDefaultCoupons()
  }
}

// 保存用户优惠券
export function saveUserCoupons() {
  try {
    const userId = getUserId()
    const storageKey = `userCoupons_${userId}`
    localStorage.setItem(storageKey, JSON.stringify(coupons.value))
  } catch (error) {
    console.error('保存优惠券失败:', error)
  }
}

// 获取所有优惠券
export function getAllCoupons() {
  return coupons.value
}